define('tree',['jquery','form'],function($,form){
    var Tree = function(options){
        var that = this,config = $.extend({},{
            ele:'',
            showCheckbox:true,
            checkboxName:'',
            expandAll:false,
            idName:'id',
            pidName:'pid',
            childenName:'children',
            content:'',
            indent:16,
            expandeds:[],//默认选中的选项
            checkeds:[],
            data:[],
        },options);
        that.config = config;
        if(typeof that.config.ele === "string"){
            that.dom = $(that.config.ele)[0];
        }else{
            that.dom = that.config.ele;
        }
        $(that.dom).addClass('aiui-tree');
        //数据整理
        if(config.data && config.data.url){

        }else{
            that.data = $.extend({},config.data);
            that.render();
        }
    },
    thisTree = function(){
        var that = this,config = that.config;
        return {
            config:config,
            getChecked:function(){
                var returns=[],list= that.checkeds.slice();
                $.each(list,function(i,item){
                    delete item[config.childenName];
                    returns.push(item);
                })
                return returns;
            },
            setChecked:function(value){
                that.setChecked.call(that,value,true);
            }
        }
    };
    /**
     * 渲染的主方法
     */
    Tree.prototype.render = function(){
        var that = this,data = that.data,config=that.config
        innerDom = that.view(data,1);
        that.listData = [];
        $(that.dom).html(''),that.innerDom = $(innerDom)[0];
        $(that.dom).append(that.innerDom);
        form.render(that.innerDom,'checkbox');
        //获取list
        var digui = function($data,pid){
            var listData = [];
            $.each($data,function(i,item){
                item[config.pidName] = pid;
                listData.push(item);
                if(item[config.childenName] && $.isArray(item[config.childenName])){
                    listData = listData.concat(digui(item[config.childenName],item[config.idName]));
                }
            })
            return listData;
        };
        that.listData = digui(that.data,0);
        that.checkeds = [],that.checkedIds=[];
        //设置事件
        that.setEvent();
    }
    /**
     * 获取选中的checkbox选中的value
     * @param {Integer} $checked 选中
     * @param {Boolean} isCheck 是否选中，true为选中，fase为取消选中
     */
    Tree.prototype.getCurrent = function($checked,isCheck){
        var that=this,config = that.config,checkeds=[],data = $.extend({},that.listData);
        var shangji = function($checkid){
            var returns = [];
            $.each(data,function(i,item){
                if(item[config.idName]==$checkid){
                    returns.push(item);
                    if(item[config.pidName]!=0){
                        returns = returns.concat(shangji(item[config.pidName]));
                    }
                }
            })
            return returns;
        };
        var xiaji = function($checkid){
            var returns = [];
            $.each(data,function(i,item){
                if(item[config.idName]==$checkid){
                    if(item[config.childenName] && $.isArray(item[config.childenName])){
                        $.each(item[config.childenName],function(i2,item2){
                            if(!item2.disabled){
                                returns.push(item2);
                            }
                            returns = returns.concat(xiaji(item2[config.idName]));
                        })
                    }
                }
            })
            return returns;
        }
        checkeds = shangji($checked).concat(xiaji($checked))
        if(isCheck){
            $.each(checkeds,function(i,item){
                //如果当前节点不在数组中则加入
                if($.inArray(item[config.idName],that.checkedIds)==-1){
                    that.checkedIds.push(item[config.idName]);
                }
            })
        }else{
            $.each(checkeds,function(i,item){
                //如果当前节点不在数组中则加入
                that.checkedIds.splice($.inArray(item[config.idName],that.checkedIds),1);
            })
            //递归检查如果有下级节点已经选中，则上级节点也选中
            var checktreeChecked = function(list){
                $.each(list,function(i,id){
                    var item = function(){
                        var temp = '';
                        $.each(that.listData,function(i3,item3){
                            if(id==item3[config.idName]){
                                temp = $.extend(true,{},item3);
                            }
                        })
                        return temp;
                    }();
                    if(item[config.pidName]!=0){
                        $.each(that.listData,function(i2,item2){
                            if(item2[config.idName]==item[config.pidName] && $.inArray(item2[config.idName],that.checkedIds)==-1){
                                that.checkedIds.push(item2[config.idName]);
                                checktreeChecked(that.checkedIds);
                            }
                        })
                    }
                })
            }
            checktreeChecked(that.checkedIds);
        }
        that.checkeds = function(){
            var checkeds = [];
            $.each(that.listData,function(i4,item4){
                if($.inArray(item4[config.idName],that.checkedIds)!=-1){
                    checkeds.push(item4);
                }
            })
            return checkeds;
        }();
        return that.checkeds;
    }
    /**
     * 递归获取dom
     */
    Tree.prototype.view = function(data,leve){
        var that = this,config=that.config,innerDom='';
        $.each(data,function(i,item){
            var innerhtml = '<div role="treeitem" data-key="{{'+config.idName+'}}" class="aiui-tree-node'+function(){
                if(item.expanded || $.inArray(item[config.idName],config.expanded)!=-1 || config.expandAll){
                    return ' is-expanded'
                }else{
                    return '';
                }
            }()+' is-focusable">'+function(){
                return '<div class="aiui-tree-node-content" style="padding-left:'+((leve-1)*config.indent)+'px"><i class="'+function(){
                    if(!item[config.childenName]){
                        return 'is-leaf ';
                    }
                    return '';
                }()+'aiui-tree-node-expand-icon aiui-icon-caret-right'+function(){
                    if(item.expanded || $.inArray(item[config.idName],config.expandeds)!=-1 || config.expandAll){
                        return ' expanded';
                    }else{
                        return '';
                    }
                }()+'"></i>'+function(){
                    if(config.showCheckbox){
                        return '<input class="tree-checkedbox" name="'+config.checkboxName+'" type="checkbox" '+function(){
                            if(item.checked || $.inArray(item[config.idName],config.checkeds)!=-1 || config.checkedAll){
                                return 'checked="checked"';
                            }else{
                                return '';
                            }
                        }()+function(){
                            if(item.disabled){
                                return ' disabled="true"'
                            }else{
                                return '';
                            }
                        }()+' aiui-checkbox value="{{'+config.idName+'}}">';
                    }
                }()+'<span class="aiui-tree-node-label">'+item.label+'</span></div>';
            }()+function(){
                if(item[config.childenName] && $.isArray(item[config.childenName])){
                    return '<div role="group" class="aiui-tree-node-childen" '+function(){
                        if(item.expanded || $.inArray(item[config.idName],config.expandeds)!=-1 || config.expandAll){
                            return 'style="display:block"';
                        }else{
                            return 'style="display:none"';
                        }
                    }()+'>'+that.view(item[config.childenName],leve+1)+'</div>';
                }else{
                    return '';
                }
            }()+'</div>';
            innerDom += aiui.render(innerhtml,item)
        })
        return innerDom;
    }
    /**
     * 设置事件
     */
    Tree.prototype.setEvent = function(){
        var that = this,$dom = $(that.dom),data=that.data,config=that.config;
        //aiui-tree-node点击事件
        $dom.find('.aiui-tree-node').on('click',function(e){
            if($(e.target).hasClass('aiui-checkbox') || $(e.target).hasClass('aiui-checkbox-input-inner') || $(e.target).hasClass('aiui-checkbox-input')){
                return false;
            }
            $clickDom= $(this);
            transitionDom = $clickDom.children('.aiui-tree-node-childen')
            if($clickDom.hasClass('is-expanded')){
                transitionDom.hide(300);
                $clickDom.children('.aiui-tree-node-content').find('.aiui-tree-node-expand-icon').removeClass('expanded');
                $clickDom.removeClass('is-expanded');
            }else{
                transitionDom.show(300);
                $clickDom.children('.aiui-tree-node-content').find('.aiui-tree-node-expand-icon').addClass('expanded');
                $clickDom.addClass('is-expanded');
            }
            e.stopPropagation();
        })
        //选择框选中事件
        $('input[aiui-checkbox][type="checkbox"]').on('change',function(e){
            var $checkbox = $(this),value=$checkbox.val();
            that.setChecked(value,$checkbox.attr('checked')=='checked');
        })
                            
    }
    /**
     * 设置节点选中
     */
    Tree.prototype.setChecked = function($value,ischeck){
        var that = this,config=that.config;
        checklist = that.getCurrent($value,ischeck);
        //消除所有的选中
        $(that.innerDom).find('input.tree-checkedbox[type="checkbox"][aiui-checkbox]').removeAttr('checked');
        //设置当前选中
        $.each(checklist,function(i,item){
            $(that.innerDom).find('input[type="checkbox"][aiui-checkbox][value="'+item[config.idName]+'"]').attr('checked','checked')
        })
        form.render(that.innerDom,'checkbox');
    }
    /**
     * 自动初始化
     */
    Tree.init = function(options){
        var initDom = $('div[aiui-tree]').each(function(i1,item){
            options = $.extend({},options,{
                ele:item
            });
            var inst = new Tree(options);
            return thisTree.call(inst);
        })
    }
    /**
     * 渲染
     */
    Tree.render = function(options){
        var inst = new Tree(options);
        return thisTree.call(inst);
    }
    return Tree;
})